package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.utlis.SendMessageUtils;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.service.DiChargesDeptService;
import com.sumainfor.pc.gmio.service.HoTenantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 服务管家租客管理
 */
@Service
public class HoTenantSerivceImpl implements HoTenantService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HoTenantSerivceImpl.class);
    @Autowired
    private HoTenantMapper hoTenantMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private HoEleMeterMapper hoEleMeterMapper;
    @Autowired
    private HoWaterMeterMapper hoWaterMeterMapper;
    @Autowired
    private HoGasMeterMapper hoGasMeterMapper;
    @Autowired
    private SeTenantBillMapper seTenantBillMapper;
    /**
     * 发送智能门锁密码的短信通知
     */
    @Override
    public JsonResult sendPassWordMessage(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        if(params.get("identifierList")==null || params.get("address")==null || params.get("phone")==null){
            return result.putFailed("参数不正确");
        }
        //智能设备的数据
        List<Map<String,Object>> identifierList=(List<Map<String,Object>>)params.get("identifierList");
        //短信参数对象
        Map<String,Object> messageMap=new HashMap<String,Object>();
        String passWord="";//密码内容
        messageMap.put("title","【上海唐巢公寓】");
        messageMap.put("address",params.get("address"));

        messageMap.put("validity","此密码在当天内有效，且只能使用一次");
        messageMap.put("phone",params.get("phone"));
        for (Map<String,Object> InteMap:identifierList){
            //Intelligent 0.蜂电   1.大华   2.科技侠   3.果加
            if (InteMap.get("Intelligent").toString().equals("2")){
                String DeviceLockToken=redisUtils.get("DeviceLockToken");
                //如果获取不到就重新登录
                if (DeviceLockToken==null){
                    Map<String,Object> tokenMap=new HashMap<String, Object>();
                    params.put("client_id", InteDeviceLockConfig.CLIENT_ID);
                    params.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
                    params.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                    params.put("username",InteDeviceLockConfig.USERNAME);
                    params.put("password",InteDeviceLockConfig.PASSWORD);
                    params.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
                    tokenMap= InteDeviceLockUtil.oauth2Token(params);
                    if (tokenMap.get("access_token")!=null){
                        DeviceLockToken=tokenMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }
//                num2++;
                params.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                params.put("accessToken",DeviceLockToken);//访问令牌
                params.put("lockId",InteMap.get("Identifier"));//智能设备编号
                params.put("keyboardPwdVersion","4");//键盘密码版本, 三代锁的密码版本为4
                params.put("keyboardPwdType","1");//参数值 单次	1
                //密码有效时间
                //获取当前时间
                params.put("startDate", InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),0,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                //获取一个小时之后的时间
                params.put("endDate",InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),2*60*60*1000,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                params.put("date",InteDeviceLockUtil.getTimeSign());
                System.out.println("params:"+params);
                Map<String,Object> map= InteDeviceLockUtil.keyboardPwdGet(params);
                System.out.println("map:"+map);
                if (map.get("keyboardPwd")!=null){
//                    passWord=passWord+InteMap.get("HouConName")+":"+map.get("keyboardPwd")+",";
                    passWord=passWord+map.get("keyboardPwd");
                    InteMap.putAll(map);
//                    num++;
                }else{
                    return result.putFailed("服务器繁忙");
                }
            }else if(InteMap.get("Intelligent").toString().equals("3")){
                String GuoJiaToken=redisUtils.get("GuoJiaToken");
                //如果获取不到就重新登录
                if (GuoJiaToken==null){
                    Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                    guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                    guoJiaMap.put("version","1");
                    com.alibaba.fastjson.JSONObject bodyJson=new com.alibaba.fastjson.JSONObject();
                    //key
                    DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                    //密码
                    bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
                    bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                    guoJiaMap=InteGuoJiaUtil.login(guoJiaMap,bodyJson);
                    //返回的token数据
                    Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
                    if (guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                        GuoJiaToken=dataMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }
//                num2++;
                Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                guoJiaMap.put("version","1");
                guoJiaMap.put("access_token",GuoJiaToken);
                com.alibaba.fastjson.JSONObject bodyJson=new com.alibaba.fastjson.JSONObject();
                bodyJson.put("lock_no",InteMap.get("Identifier"));//智能设备编号
                bodyJson.put("pwd_user_mobile","15703928772");
                System.out.println("guoJiaMap:"+guoJiaMap);
                //发送键密码
                Map<String,Object> map=InteGuoJiaUtil.temp_pwd(guoJiaMap,bodyJson);
                DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                String d2="";
                try {
                    Map<String,Object> dataMap=(Map<String,Object>)map.get("data");
                    d2 = desPlus2.decrypt(DESEncrypt.byteArr2HexStr(DESEncrypt.hexStringToBytes(dataMap.get("pwd_text").toString())));
                }catch (Exception e){
                    log.debug("键盘密码解密错误"+e);
                }
                if (map.get("rlt_code").toString().equals("HH0000")){//HH0000 请求成功
//                    passWord=passWord+InteMap.get("HouConName")+":"+d2+",";
                    passWord=passWord+d2;
                    InteMap.put("keyboardPwd",d2);
                    InteMap.putAll(map);
//                    num++;
                }else{
                    return result.putFailed("服务器繁忙");
                }
                InteMap.putAll(map);
            }
        }
        messageMap.put("password",passWord);
        System.out.println("短信参数:"+messageMap);

        //发送短信
        Map<String, Object> resultMap=SendMessageUtils.sendPassWord(messageMap);
        System.out.println("短信返回值:"+resultMap);
        if (resultMap.get("errorCode")!=null && String.valueOf(resultMap.get("errorCode").toString()).equals("200")){
            result.putSuccess("操作成功");
        }else{
            result.putFailed("服务繁忙");
        }
        return result;
    }
    /**
     * 租赁顾问新签合同时抄水电燃表
     *
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHoWegMeter (Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            /*电表开始*/
            try {
                Map<String,Object> HoMap=new HashMap<String,Object>();
                //批次电表记录编号
                String UUID3="";
                //电表抄表编号
                String UUID="";
                int number=0;
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ElemeId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_ele_meter");
                }});
                //账单支出编号
                String UUID2="";
                int number2=0;
                Map<String,Object>uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "BiId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_tenant_bill");
                }});
                number=uuid!=null &&(!uuid.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid.get("uuid").toString()):0;
                number2=uuid2!=null &&(!uuid2.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid2.get("uuid").toString()):0;
                UUID3=ComUtils.getLocalTrmSeqNum("ba"+0,number);//账单批次编号
                HoMap.put("by", ContextUtils.getUserId());//操作人
                HoMap.put("Recorder",ContextUtils.getUserId());// 电表记录人编号
                HoMap.put("IfGenerate",1);//是否生成账单  0.未生成  1.已生成',
                HoMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                HoMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(HoMap);
                HoMap.put("BiType",2);// 1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                HoMap.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是,
                HoMap.put("CreateType","2");//房源详表
                HoMap.put("Create",ContextUtils.getUserId());//账单创建人
                HoMap.put("Status",1);//账单状态   1.待支付  2.支付完成
                HoMap.put("GenerateTime",HoMap.get("instm"));//账单生成日期
                HoMap.put("BiGenerated",HoMap.get("instm"));//账单生成日期
                HoMap.put("StaTime",HoMap.get("GenerateTime"));//账单周期--开始时间
                HoMap.put("EndTime", ConvertDateTime.dateFormatTimeToStr(ConvertDateTime.FORMAT_ONLY_DATE_EN,ConvertDateTime.addDateTime(ConvertDateTime.getCurDate(),15,4)));//账单周期--结束时间
                HoMap.put("LateDay",HoMap.get("EndTime"));//最晚付款时间
                List<Map<String,Object>> listMap=(List<Map<String,Object>>)params.get("eleData");
                System.out.println("listMAp:"+listMap);
                Calendar now = Calendar.getInstance();
                int month= (now.get(Calendar.MONTH) + 1);
                int num=0;
                int num2=0;
                for (Map<String,Object> arrMap:listMap){
                    UUID= ComUtils.getLocalTrmSeqNum("em"+num,number);//电表抄表记录编号
                    UUID2=ComUtils.getLocalTrmSeqNum("zdzc"+num,number2);//账单编号
                    arrMap.putAll(HoMap);
                    arrMap.put("ElemeId",UUID);
                    arrMap.put("BatchId",UUID3);
                    hoEleMeterMapper.addHoEleMeter(arrMap);
                    //收入账单
                    arrMap.put("BiId",UUID2);
                    arrMap.put("BiName",month+"月份电费账单");
                    arrMap.put("BiMoney",arrMap.get("BillMoney"));//账单金额
                    arrMap.put("BiName",month+"月份电费账单");
                    arrMap.put("Source",UUID);//来源编号
                    arrMap.put("BillExplain","电费:"+arrMap.get("BiMoney")+",均摊电量:"+arrMap.get("perEleNum"));
                    arrMap.put("PubType",2);//1.水费  2.电费  3.燃气',
                    if (arrMap.get("IfOperaType").toString().equals("0")
                            && arrMap.get("TenId")!=null && !arrMap.get("TenId").toString().equals("")){
                        seTenantBillMapper.addTenantBill(arrMap);
                    }
                    num++;
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            /*电表结束*/

            /*水表开始*/
            try {
                Map<String,Object> HoMap=new HashMap<String,Object>();
                //水表批次编号
                String UUID3="";
                //水电抄表编号
                String UUID="";
                int number=0;
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "WameId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_water_meter");
                }});
                //账单支出编号
                String UUID2="";
                int number2=0;
                Map<String,Object>uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "BiId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_tenant_bill");
                }});

                number=uuid!=null &&(!uuid.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid.get("uuid").toString()):0;
                number2=uuid2!=null &&(!uuid2.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid2.get("uuid").toString()):0;

                HoMap.put("by", ContextUtils.getUserId());//操作人
                HoMap.put("Recorder",ContextUtils.getUserId());// 水表记录人编号
                HoMap.put("IfGenerate",1);//是否生成账单  0.未生成  1.已生成',
                HoMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                HoMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(HoMap);
                HoMap.put("GenerateTime",HoMap.get("instm"));//账单生成日期
                HoMap.put("StaTime",HoMap.get("GenerateTime"));//账单周期--开始时间
                HoMap.put("EndTime",ConvertDateTime.dateFormatTimeToStr(ConvertDateTime.FORMAT_ONLY_DATE_EN,ConvertDateTime.addDateTime(ConvertDateTime.getCurDate(),15,4)));//账单周期--结束时间

                Calendar now = Calendar.getInstance();
                int month= (now.get(Calendar.MONTH) + 1);
                int num=0;
                //水表的数据
                Map<String,Object> waterData=(Map<String,Object>)params.get("waterData");
                //水表记录对应的账单数据
                List<Map<String,Object>> waterList=(List<Map<String,Object>>)waterData.get("waterList");
                System.out.println("waterData:"+waterData);
                UUID= ComUtils.getLocalTrmSeqNum("wm"+num,number);//水表抄表记录编号
                UUID3=ComUtils.getLocalTrmSeqNum("ba"+num,number);
                waterData.putAll(HoMap);
                System.out.println("水表新增的记录:"+waterData);
                waterData.put("WameId",UUID);
                waterData.put("BatchId",UUID3);
                hoWaterMeterMapper.addHoWaterMeter(waterData);
                for (int i=0;i<waterList.size();i++){
                    UUID2=ComUtils.getLocalTrmSeqNum("zdzc"+num,number2);//账单编号
                    Map<String,Object>billMap=waterList.get(i);
                    //收入账单
                    billMap.put("instm",HoMap.get("instm"));
                    billMap.put("insterm",HoMap.get("insterm"));
                    billMap.put("insby",HoMap.get("insby"));
                    billMap.put("insfnc",HoMap.get("insfnc"));
                    billMap.put("BiGenerated",HoMap.get("instm"));//账单生成日期
                    billMap.put("BiId",UUID2);
                    billMap.put("BiName",month+"月份水费账单");
                    billMap.put("BiType","2");//账单类型  1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                    billMap.put("LateDay",HoMap.get("EndTime"));//最晚付款时间
                    billMap.put("EndTime",billMap.get("LateDay"));//账单结束时间 计算十五天之后的时间、
                    billMap.put("BiName",month+"月份水费账单");
                    billMap.put("Source",UUID);//来源编号
                    billMap.put("BillExplain","水费:"+billMap.get("BiMoney"));
                    billMap.put("BiType",2);// 1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                    billMap.put("PubType",1);//1.水费  2.电费  3.燃气',
                    billMap.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是,
                    billMap.put("CreateType","2");//房源详表
                    billMap.put("Create",ContextUtils.getUserId());//账单创建人
                    if (billMap.get("TenId")!=null && !billMap.get("TenId").toString().equals("")){
                        seTenantBillMapper.addTenantBill(billMap);
                        num++;
                    }
                }

                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            /*水表结束*/

            /*燃气表开始*/
            try {
                Map<String,Object> HoMap=new HashMap<String,Object>();
                //燃气批次编号
                String UUID3="";
                //燃气抄表编号
                String UUID="";
                int number=0;
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "GasmeId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_gas_meter");
                }});
                //账单支出编号
                String UUID2="";
                int number2=0;
                Map<String,Object>uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "BiId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_tenant_bill");
                }});

                number=uuid!=null &&(!uuid.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid.get("uuid").toString()):0;
                number2=uuid2!=null &&(!uuid2.get("uuid").toString().equals("")) ?
                        Integer.valueOf(uuid2.get("uuid").toString()):0;

                HoMap.put("by", ContextUtils.getUserId());//操作人
                HoMap.put("Recorder",ContextUtils.getUserId());// 电表记录人编号
                HoMap.put("IfGenerate",1);//是否生成账单  0.未生成  1.已生成',
                HoMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                HoMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(HoMap);
                HoMap.put("GenerateTime",HoMap.get("instm"));//账单生成日期

                HoMap.put("StaTime",HoMap.get("GenerateTime"));//账单周期--开始时间
                HoMap.put("EndTime",ConvertDateTime.dateFormatTimeToStr(ConvertDateTime.FORMAT_ONLY_DATE_EN,ConvertDateTime.addDateTime(ConvertDateTime.getCurDate(),15,4)));//账单周期--结束时间

                Calendar now = Calendar.getInstance();
                int month= (now.get(Calendar.MONTH) + 1);
                int num=0;
                Map<String,Object> gasData=(Map<String,Object>)params.get("gasData");
                System.out.println("gasData:"+gasData);
                List<Map<String,Object>> billList=(List<Map<String,Object>>)gasData.get("gasList");
                UUID= ComUtils.getLocalTrmSeqNum("gm"+num,number);//燃气表抄表记录编号
                UUID3=ComUtils.getLocalTrmSeqNum("ba"+num,number);
                gasData.putAll(HoMap);
                gasData.put("GasmeId",UUID);
                gasData.put("BatchId",UUID3);
                hoGasMeterMapper.addHoGasMeter(gasData);
                for (int i=0;i<billList.size();i++){
                    UUID2=ComUtils.getLocalTrmSeqNum("zdzc"+num,number2);//账单编号
                    Map<String,Object>billMap=billList.get(i);
                    //收入账单
                    billMap.put("instm",HoMap.get("instm"));
                    billMap.put("insterm",HoMap.get("insterm"));
                    billMap.put("insby",HoMap.get("insby"));
                    billMap.put("insfnc",HoMap.get("insfnc"));
                    billMap.put("BiGenerated",HoMap.get("instm"));//账单生成日期
                    billMap.put("BiId",UUID2);
                    billMap.put("BiName",month+"月份燃气账单");
                    billMap.put("BiType","2");//账单类型  1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                    billMap.put("LateDay",HoMap.get("EndTime"));//最晚付款时间
                    billMap.put("EndTime",billMap.get("LateDay"));//账单结束时间 计算十五天之后的时间、
                    billMap.put("BiName",month+"月份燃气账单");
                    billMap.put("Source",UUID);//来源编号
                    billMap.put("BillExplain","燃气费:"+billMap.get("BiMoney"));
                    billMap.put("PubType",3);//1.水费  2.电费  3.燃气',
                    billMap.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是,
                    billMap.put("CreateType","2");//房源详表
                    billMap.put("Create",ContextUtils.getUserId());//账单创建人
                    if (billMap.get("TenId")!=null && !billMap.get("TenId").toString().equals("")) {
                        seTenantBillMapper.addTenantBill(billMap);
                        num++;
                    }
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            /*燃气表结束*/
        }
        finally {
            lock.unlock();
        }
        return result;
    }
}
